import uuid
import base64
import hashlib

from django.conf import settings

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend


def md5(args):
    obj = hashlib.md5(settings.SECRET_KEY.encode('utf8'))
    obj.update(args.encode('utf-8'))
    return obj.hexdigest()


def uid(args):
    data = f"{str(uuid.uuid4())}-{args}"
    return md5(data)


class Password:
    def __init__(self):
        # 配置密钥和初始化向量（IV）
        # 注意：在生产环境中，密钥和IV应妥善保管，且IV应该是随机生成的
        self.KEY = settings.SECRET_KEY.encode('utf-8')[:32]  # AES-256需要32字节密钥
        # self.IV = os.urandom(16)  # AES块大小为16字节
        self.IV = b'\xce\xc9\xc6.\x8fj\x17A\x84g\\\x99\x1a \xea\xd7'

    def pad(self, data):
        padder = padding.PKCS7(128).padder()
        padded_data = padder.update(data.encode('utf-8')) + padder.finalize()
        return padded_data

    def unpad(self, padded_data):
        unpadder = padding.PKCS7(128).unpadder()
        return unpadder.update(padded_data) + unpadder.finalize()

    def encrypt(self, plaintext):
        cipher = Cipher(algorithms.AES(self.KEY), modes.CBC(self.IV), backend=default_backend())
        encryptor = cipher.encryptor()
        padded_text = self.pad(plaintext)
        ciphertext = encryptor.update(padded_text) + encryptor.finalize()
        return base64.b64encode(ciphertext).decode('utf-8')

    def decrypt(self, ciphertext_b64):
        ciphertext = base64.b64decode(ciphertext_b64)
        cipher = Cipher(algorithms.AES(self.KEY), modes.CBC(self.IV), backend=default_backend())
        decryptor = cipher.decryptor()
        padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
        plaintext = self.unpad(padded_plaintext).decode('utf-8')
        return plaintext


if __name__ == '__main__':
    # 使用示例
    original_text = "敏感信息"
    password = Password()
    encrypted_text = password.encrypt(original_text)
    print(f"加密后的文本: {encrypted_text}")

    decrypted_text = password.decrypt(encrypted_text)
    print(f"解密后的文本: {decrypted_text}")
